package com.nisco.nio.channel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 通过fileChannel写入数据
 **/
public class FileChannelWrite {
    public static void main(String[] args)
        throws IOException {
        RandomAccessFile rf = new RandomAccessFile("E:/aa.txt", "rw");
        FileChannel channel = rf.getChannel();

        // 通道的长度就是物理文件的长度
        System.out.println(channel.size());
        // 默认位置为0
        System.out.println(channel.position());
        ByteBuffer buffer = ByteBuffer.allocate(100);

        // put buffer
        buffer.put("调皮，哈哈".getBytes());
        buffer.flip();

        int i = 0;
        // 产生空洞
//        channel.position(10240);
        while (buffer.hasRemaining()) {
            channel.write(buffer);
            System.out.println(++i);
        }
        channel.force(true);  // 将通道里为写入磁盘的数据强制写入

        System.out.println(channel.position());
        System.out.println(channel.size());
        FileChannel truncate = channel.truncate(10240);// 截取指定字节文件



        channel.close();
        rf.close();
    }
}
